#include "MediaDataHandler.h"
#include "Manager.h"
#include "common.h"

CMediaDataHandler::CMediaDataHandler(CManager *pMan)
: m_bExit(false)
, m_pMan(pMan)
{
	StartThread();
}

CMediaDataHandler::~CMediaDataHandler(void)
{
	m_bExit = true;

	WaitForStop();

	while (m_lstMedia.size())
	{
		MediaInfo *pMedia = NULL;

		{
			CAutoLock autoLock(&m_lockMedia);
			pMedia = (MediaInfo *)m_lstMedia.front();
			m_lstMedia.pop_front();
		}	

		if (pMedia)
		{
			if (pMedia->pData)
			{
				delete [] pMedia->pData;
				pMedia->pData = NULL;
			}

			delete pMedia;
			pMedia = NULL;				
		}			
	}
}

void CMediaDataHandler::PutData(const char *pData, int nDataLen, int nDataType /*= 1*/)
{
	MediaInfo *pMedia = new MediaInfo;
	if (pMedia)
	{
		pMedia->nDataLen = nDataLen;
		pMedia->nDataType = nDataType;
		pMedia->pData = new char[nDataLen];
		if (pMedia->pData)
		{
			memcpy(pMedia->pData, pData, nDataLen);

			CAutoLock autoLock(&m_lockMedia);
			m_lstMedia.push_back(pMedia);
		}
		else
		{
			delete pMedia;
			pMedia = NULL;
		}
	}
}

void CMediaDataHandler::ThreadProcMain(void)
{
	HandleMediaData();
}

void CMediaDataHandler::HandleMediaData(void)
{
	while (!m_bExit)
	{
		while (m_lstMedia.size() && !m_bExit)
		{
			MediaInfo *pMedia = NULL;

			{
				CAutoLock autoLock(&m_lockMedia);
				pMedia = (MediaInfo *)m_lstMedia.front();
				m_lstMedia.pop_front();
			}	

			if (pMedia)
			{
				if (pMedia->pData)
				{
					if (pMedia->nDataType == 1)
						m_pMan->SendMediaToServer(SCREEN_DATA, pMedia->pData, pMedia->nDataLen);
					else
						m_pMan->SendMediaToServer(AUDIO_DATA, pMedia->pData, pMedia->nDataLen);						

					delete [] pMedia->pData;
					pMedia->pData = NULL;
				}

				delete pMedia;
				pMedia = NULL;				
			}			
		}

		my_sleep(5);
	}
}
